package com.imooc.dianping.controller.admin;

import com.imooc.dianping.common.AdminPermission;
import com.imooc.dianping.common.BusinessException;
import com.imooc.dianping.common.CommonUtil;
import com.imooc.dianping.common.EmBusinessError;
import com.imooc.dianping.model.Shop;
import com.imooc.dianping.request.PageInfo;
import com.imooc.dianping.request.PageQuery;
import com.imooc.dianping.request.ShopCreateReq;
import com.imooc.dianping.service.ShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin/shop")
public class AdminShopController {

    @Autowired
    private ShopService shopService;

    //门店列表
    @RequestMapping("/index")
    @AdminPermission
    public String index(PageQuery pageQuery, Model model){

        model.addAttribute("data", shopService.selectAll(pageQuery));
        model.addAttribute("CONTROLLER_NAME", "shop");
        model.addAttribute("ACTION_NAME", "index");
        return "/admin/shop/index";
    }

    @RequestMapping("/createpage")
    @AdminPermission
    public String createPage(Model model){
        model.addAttribute("CONTROLLER_NAME","shop");
        model.addAttribute("ACTION_NAME","create");
        return "/admin/shop/create";
    }

    @RequestMapping(value = "/create",method = RequestMethod.POST)
    @AdminPermission
    public String create(@Valid ShopCreateReq shopCreateReq, BindingResult bindingResult) throws BusinessException {
        if(bindingResult.hasErrors()){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, CommonUtil.processErrorString(bindingResult));
        }
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopCreateReq,shop);
        shopService.create(shop);
        return "redirect:/admin/shop/index";


    }

}
